<template>
  <div class="app-container">
    <el-row
      :gutter="15"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:dept:add']"
          icon="el-icon-plus"
          plain
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-sort"
          plain
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          @click="setAreaByAncestorsIsNull"
        >生成组级列表</el-button>
      </el-col>
      <el-form
        v-show="showSearch"
        ref="queryForm"
        :inline="true"
        :model="queryParams"
        class="el-form-search"
      >
        <el-form-item
          class="el-form-search-item"
          label="地区名称"
          prop="name"
        >
          <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入地区名称"
            size="mini"
            style="width: 140px"
          />
        </el-form-item>
        <el-form-item
          class="el-form-search-item"
          label="状态"
          prop="status"
        >
          <el-select
            v-model="queryParams.status"
            clearable
            placeholder="地区状态"
            size="mini"
            style="width: 140px"
          >
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="el-form-search-item">
          <el-button
            icon="el-icon-search"
            size="mini"
            type="primary"
            @click="handleQuery"
          >搜索
          </el-button>
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
          >重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="areaList"
      :default-expand-all="isExpandAll"
      :expand-row-keys="expandedRowKeys"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      highlight-current-row
      row-key="num"
      border
      stripe
    >
      <el-table-column
        :show-overflow-tooltip="true"
        align="left"
        header-align="center"
        label="地区名称"
        prop="name"
        width="300"
      ></el-table-column>
      <el-table-column
        :show-overflow-tooltip="true"
        align="center"
        header-align="center"
        label="地区编码"
        prop="code"
      />
      <el-table-column
        align="center"
        label="状态"
        prop="status"
        width="120"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:dept:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            v-hasPermi="['system:dept:add']"
            icon="el-icon-plus"
            size="mini"
            type="text"
            @click="handleAdd(scope.row)"
          >新增
          </el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            v-hasPermi="['system:dept:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      append-to-body
      width="600px"
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="left"
      >
        <el-row :gutter="15">
          <el-col
            v-if="form.parentId !== 0"
            :span="24"
          >
            <el-form-item
              label="上级地区"
              prop="parentId"
            >
              <treeselect
                v-model="form.parentId"
                :normalizer="normalizer"
                :options="areaOptions"
                placeholder="选择上级地区"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item
              label="地区名称"
              prop="name"
            >
              <el-input
                v-model="form.name"
                placeholder="请输入地区名称"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item
              label="地区编码"
              prop="code"
            >
              <el-input
                v-model="form.code"
                placeholder="请输入地区代码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="地区状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
} from "@/api/system/dept";
import {
  listArea,
  addArea,
  getArea,
  listAreaExcludeChild,
  updateArea,
  deleteArea,
  setAreaByAncestorsIsNull,
} from "@/api/maintenance/area";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Area",
  dicts: ["sys_normal_disable"],
  components: { Treeselect },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 接受没有处理成树的数据
      areaListData: [],
      // 表格树数据
      areaList: [],
      // 地区树选项
      areaOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        name: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级地区不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "地区名称不能为空", trigger: "blur" },
        ],
        code: [
          { required: true, message: "地区编码不能为空", trigger: "blur" },
          { min: 6, max: 6, message: "地区编码长度是6位", trigger: "blur" },
        ],
        // email: [
        //   {
        //     type: "email",
        //     message: "'请输入正确的邮箱地址",
        //     trigger: ["blur", "change"],
        //   },
        // ],
        // phone: [
        //   {
        //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        //     message: "请输入正确的手机号码",
        //     trigger: "blur",
        //   },
        // ],
      },
      expandedRowKeys: [],
    };
  },
  created () {
    this.getList();
  },
  methods: {
    /** 查询部门列表 */
    getList () {
      this.loading = true;

      listArea(this.queryParams).then((response) => {
        // console.info(response.data);
        // 将数据转换成树，展示到表格中
        this.areaList = this.handleTree(response.data, "num"); 
        // 接受初始数据，过滤数据赋值给expandedRowKeys
        this.areaListData = response.data
        



        // this.expandedRowKeys = this.areaListData
        //   .filter(item => item.parentId === 1 || item.parentId === null)
        //   .map(item => (item.num).toString());

        // console.log(this.areaList);

        this.expandedRowKeys = this.areaListData.reduce((expandedRowKeys, areaItem) => {
          // 检查parentId是否满足特定条件
          if (areaItem.parentId === 1 || areaItem.parentId === null) {
            // 如果满足条件，则将num添加到结果数组中
            expandedRowKeys.push(areaItem.num.toString());
          }
          return expandedRowKeys; // 返回累加的结果数组
        }, []);
        // this.expandedRowKeys = ['1', '130000']
        console.log(this.expandedRowKeys);

        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.num,
        label: node.name,
        children: node.children,
      };
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        num: undefined,
        parentId: undefined,
        name: undefined,
        code: undefined,
        status: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.num;
      }
      this.open = true;
      this.title = "添加地区";
      listArea().then((response) => {
        this.areaOptions = this.handleTree(response.data, "num");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll () {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      getArea(row.num).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改地区";
        console.info(this.form);
      });
      listAreaExcludeChild(row.num).then((response) => {
        this.areaOptions = this.handleTree(response.data, "num");
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.num != undefined) {
            updateArea(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArea(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$modal
        .confirm("确认删除吗？")
        .then(function () {
          return deleteArea(row.num);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    setAreaByAncestorsIsNull () {
      setAreaByAncestorsIsNull().then((response) => {
        this.$modal.msgSuccess("修改祖籍列表成功！")
      })
    }
  },
};
</script>
